﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;

namespace Trade.DBUtility
{
    public class CountryFromIP
    {
        public string GetCountryFromIP(string strIP, out string strErrorMsg)
        {
            strErrorMsg = "";
            if (strIP == "127.0.0.1")
                return "-1";
            string api = "http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP;
            string str = "";
            try
            {
                WebClientEx client = new WebClientEx(500);
                str = client.DownloadString(api);
                client.Dispose();
            }
            catch (Exception ex)
            {
                strErrorMsg = ex.Message;
                return "-1";
            }
            JObject ResultParent = JObject.Parse(str);
            string trans_result = "";
            if (ResultParent["code"].ToString() == "0")
            {
                trans_result = ResultParent["data"].ToString();
                ResultParent = JObject.Parse(trans_result);
                string strobj = ResultParent["country"].ToString();
                trans_result = JsonString.GetString(strobj);
                //
                strobj = ResultParent["region"].ToString();
                trans_result = trans_result + "-" + JsonString.GetString(strobj);
            }
            if (trans_result.ToLower().IndexOf("未分配或者内网IP".ToLower()) >= 0)
                trans_result = "-1";
            return trans_result;
        }
    }
}
